import FontFaceObserver from 'fontfaceobserver'
const loadFontList = []

export function loadFont (fontName) {
  const font = window._graphFontList_.find(item => item.fontName === fontName)
  const fontUrl = font.fontFile
  return new Promise((resolve, reject) => {
    if (loadFontList.includes(fontName)) {
      resolve()
    }
    // 创建一个style标签
    const style = document.createElement('style')
    style.type = 'text/css'

    // 定义@font-face规则
    const fontFace = `
    @font-face {
      font-family: '${fontName}';
      src: url('${fontUrl}') format('truetype');
    }
  `

    // 将规则插入style标签
    if (style.styleSheet) {
      style.styleSheet.cssText = fontFace // IE8及以下
    } else {
      style.appendChild(document.createTextNode(fontFace)) // 其他浏览器
    }
    const fontObserver = new FontFaceObserver(fontName)
    fontObserver
      .load(null, 60 * 1000 * 2)
      .then(() => {
        console.log(`Font ${fontName} loaded successfully.`)
        resolve()
      })
      .catch((err) => {
        console.error(`Failed to load font: ${fontName}`, err)
        reject(err)
      })

    // 将style标签插入到head中
    document.head.appendChild(style)
    loadFontList.push(fontName)
  })
}
